package com.atguigu.gmall.order.consumer;


import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.common.constant.MqConst;
import com.atguigu.gmall.model.enums.ProcessStatus;
import com.atguigu.gmall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class DecrStockConsumer {

    @Autowired
    OrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_WARE_ORDER,durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_WARE_ORDER),
            key = MqConst.ROUTING_WARE_ORDER
    ))
    public void updateOrderStatus(String map, Message message , Channel channel){
        try {
            Map map1 = JSONObject.parseObject(map, Map.class);
            //更新订单
            if (map1.get("status").equals("DEDUCTED")){
                orderService.updateOrderStatus(Long.parseLong(String.valueOf(map1.get("orderId"))), ProcessStatus.WAITING_DELEVER);
            }else {
                //异常了
                //打印日志
                //更新订单状态
                orderService.updateOrderStatus(Long.parseLong(String.valueOf(map1.get("orderId"))),ProcessStatus.STOCK_EXCEPTION);
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
